package com.tcat.user.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tcat.common.enums.ExceptionEnum;
import com.tcat.common.exception.TcatException;
import com.tcat.common.vo.PageResult;
import com.tcat.user.mapper.UserMapper;
import com.tcat.user.pojo.Users;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import java.util.List;
@Service
public class UserService {
    @Autowired
    private UserMapper userMapper;

    public PageResult<Users> queryUsersByPage(Integer page, Integer rows, String sortBy, Boolean desc, String search) {
        //分页
        PageHelper.startPage(page,rows);
        /*
           WHERE 'name' like '%x%' OR letter =='x'
           ORDER BY id DESC
         */
        //过滤
        Example example=new Example(Users.class);
        if(StringUtils.isNotBlank(search)){
            //example.orderBy("user_id");
            example.createCriteria().orLike("name","%"+search+"%");
                    //.orEqualTo("letter",search.toUpperCase());

        }
        //排序
        if(StringUtils.isNotBlank(sortBy)){
            String orderByClause=sortBy +(desc ? " DESC":" ASC");
            example.setOrderByClause(orderByClause);
        }
        //查询
        //分页助手会拦截查询并对他进行分页
        Page<Users> list = (Page<Users>)userMapper.selectByExample(example);
        if(CollectionUtils.isEmpty(list)){
            throw new TcatException(ExceptionEnum.USER_NOT_FOUND);
        }
        //解析分页结果
        PageInfo<Users> info=new PageInfo<>(list);
        return new PageResult<>(info.getTotal(),list);
    }





    public void deleteByUsersInUrs(Long uid) {
        userMapper.deleteByUsersInUrs(uid);
    }

    /**
     * 删除品牌  单个（多个删除则每个遍历每个品牌进行删除）
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteUsers(long id) {
        userMapper.deleteByPrimaryKey(id);
        deleteByUsersInUrs(id);
    }

    /**
     * 新增用户
     * @param user
     * @param rids
     */
    @Transactional(rollbackFor = Exception.class)
    public void saveUser(Users user, List<Long> rids) {
        //新增品牌
        user.setId(null);
        int count = userMapper.insert(user);
        if(count!=1){
            throw new TcatException(ExceptionEnum.USER_SAVE_ERROR);
        }
        //新增中间表
        for(Long rid:rids){
            count = userMapper.insertUrs(user.getId(),rid);
            if(count!=1){
                throw  new TcatException((ExceptionEnum.USER_SAVE_ERROR));
            }
        }
    }

    /**
     * 用户更新
     * @param user
     * @param rids
     */
    @Transactional(rollbackFor=Exception.class)
    public void updateUser(Users user,List<Long> rids){
        deleteByUsersInUrs(user.getId());
        this.userMapper.updateByPrimaryKeySelective(user);
        for(Long rid:rids){
            this.userMapper.insertUrs(user.getId(),rid);
        }
    }


    public int countUsers(){
        List<Users> users = userMapper.selectAll();
        int size=users.size();
        return size;
    }
}
